package com.service.business.conversion.controller;

import com.google.common.collect.Maps;
import com.service.business.base.dto.LoginUserSession;
import com.service.business.conversion.controller.rep.ConversionCoinsConfigRep;
import com.service.business.conversion.controller.rep.ConvertPageRep;
import com.service.business.conversion.controller.req.ConversionReq;
import com.service.business.conversion.service.ConvertCoinsRecordService;
import com.service.business.conversion.service.ConvertConfigService;
import com.service.business.framework.log.RequestLog;
import com.service.business.member.service.MemberStoreService;
import com.service.business.support.ConversionLockUtils;
import com.service.business.support.MemberStoreLockUtils;
import com.service.business.support.SessionUtil;
import com.service.core.rest.BaseController;
import com.service.core.rest.request.PageRequest;
import com.service.core.rest.response.BaseResponse;
import com.service.core.rest.response.OneResponse;
import com.service.core.rest.response.PageResponse;
import com.service.dao.enums.CoinsEnum;
import com.service.dao.model.ConvertConfig;
import com.service.dao.model.MemberStore;
import org.redisson.RedissonRedLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <dl>
 * <dt>back-end</dt>
 * <dd>Description:</dd>
 * <dd>Copyright: Copyright (C) 2015</dd>
 * <dd>Company: </dd>
 * <dd>CreateDate: 2019年12月12日</dd>
 * </dl>
 *
 * @author
 */
@RestController
@RequestMapping("conversion-coins")
public class ConversionController extends BaseController {

    @Autowired
    private ConvertCoinsRecordService coinsRecordService;
    @Autowired
    private ConvertConfigService convertConfigService;
    @Autowired
    private MemberStoreService memberStoreService;
    @Autowired
    private SessionUtil sessionUtil;
    @Autowired
    private ConversionLockUtils lockUtils;

    @RequestLog("合成货币配置")
    @GetMapping("/config/{coinsName}")
    public OneResponse<ConversionCoinsConfigRep> getConfig(@PathVariable("coinsName") CoinsEnum coins) {
        return successQueryOneResponse(convertConfigService.config(coins));
    }

    @RequestLog("合成货币")
    @PostMapping("/conversion/{coinsName}")
    public BaseResponse conversion(@PathVariable("coinsName") CoinsEnum coins,
                                   @RequestBody @Validated ConversionReq conversionReq) {
        conversionReq.setCoins(coins);

        List<ConvertConfig> configList = convertConfigService.listByTargetCoin(coins);
        LoginUserSession session = sessionUtil.getUser();

        //加锁
        List<MemberStore> memberStores = configList.stream()
                .map(item -> memberStoreService.getMemberStore(session.getUserId(), item.getSourceCoinsName()))
                .collect(Collectors.toList());

        List<String> lockKeyArr = MemberStoreLockUtils.buildStoreKey2List(memberStores);
        lockKeyArr.add(ConversionLockUtils.LOCK_KEY);

        RedissonRedLock redLock = lockUtils.getRedLock(lockKeyArr);
        if (lockUtils.redLockTryLock(redLock)) {
            try {
                coinsRecordService.convertCoin(conversionReq, session);
            } finally {
                redLock.unlock();
            }
        }
        return successBaseResponse();
    }

    @RequestLog("合成货币配置")
    @PostMapping("/page/{coinsName}")
    public PageResponse<ConvertPageRep> pageConvertRecord(@PathVariable("coinsName") CoinsEnum coins, @RequestBody PageRequest pageRequest) {
        return successQueryPageResponse(coinsRecordService.pageRecord(coins, pageRequest));
    }


}
